/**
 * 配置浏览器本地存储的方式，可直接存储对象数组。
 */

type CacheType = 'localStorage' | 'sessionStorage'

export const CACHE_KEY = {
  // 用户相关
  ROLE_ROUTERS: 'roleRouters',
  USER: 'user',
  // 系统设置
  IS_DARK: 'isDark',
  LANG: 'lang',
  THEME: 'theme',
  LAYOUT: 'layout',
  DICT_CACHE: 'dictCache',
  // 登录表单
  LoginForm: 'loginForm',
  TenantId: 'tenantId'
}

export const useCache = (type: CacheType = 'localStorage') => {
  const storage = type === 'localStorage' ? localStorage : sessionStorage

  return {
    wsCache: {
      get: (key: string) => {
        const value = storage.getItem(key)
        try {
          return value ? JSON.parse(value) : undefined
        } catch {
          return value || undefined
        }
      },
      set: (key: string, value: any) => {
        const data = typeof value === 'string' ? value : JSON.stringify(value)
        storage.setItem(key, data)
      },
      delete: (key: string) => {
        storage.removeItem(key)
      },
      clear: () => {
        storage.clear()
      }
    }
  }
}
export const deleteUserCache = () => {
  const { wsCache } = useCache()
  wsCache.delete(CACHE_KEY.USER)
  wsCache.delete(CACHE_KEY.ROLE_ROUTERS)
  // 注意，不要清理 LoginForm 登录表单
}
